package com.example.pluginmanager.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.common.eunm.ExceptionCode;
import com.common.exception.UserInfoException;
import com.example.pluginmanager.entity.Resource;
import com.example.pluginmanager.entity.User;
import com.example.pluginmanager.entity.UserRoleRelation;
import com.example.pluginmanager.service.RoleResourceRelationService;
import com.example.pluginmanager.service.UserRoleRelationService;
import com.example.pluginmanager.service.UserService;
import com.example.pluginmanager.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/*
* 验证用户权限
* */
@Component
@Slf4j
public class ValidateUserPermissionsInterceptor implements HandlerInterceptor {

    @Autowired
    private UserRoleRelationService userRoleRelationService;

    @Autowired
    private RoleResourceRelationService roleResourceRelationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("=============================ValidateUserPermissionsInterceptor=============================");

        //路径匹配
        PathPatternParser pathPatternParser = new PathPatternParser();

        User user = ValidateJwtTokenInterceptor.userThreadLocal.get();
        log.info("user:{}",user);
        //用户所拥有的角色
        List<UserRoleRelation> userRoleRelations = userRoleRelationService.listUserRoleRelationByUserId(user.getId());
        log.info("userRole:{}",userRoleRelations);
        //所有角色id
        List<String> roleIds = userRoleRelations.stream().map(UserRoleRelation::getRoleId).collect(Collectors.toList());
        if (CollUtil.isEmpty(roleIds)){
            throw new UserInfoException(ExceptionCode.USER_INFO_EXCE.getMsg());
        }
        //查询角色所关联的资源
        List<Resource> resources = roleResourceRelationService.listRoleResourceRelation(roleIds);
        if (CollUtil.isNotEmpty(resources)) {
            user.setRoleIds(roleIds);
            //获取请求的资源路径
            String requestURI = request.getRequestURI();
            boolean isMatch = false;
            for (Resource resource : resources) {
                PathPattern parse = pathPatternParser.parse(resource.getResourcePath());// ** 代表所有子路径都可以
                boolean matches = parse.matches(PathContainer.parsePath(requestURI));
                if (matches) {
                    isMatch = true;
                    break;
                }
            }
            if (isMatch) {
                return true;
            }
            throw new RuntimeException(ExceptionCode.DENIED_ACCESS.getMsg());
        }
        throw new RuntimeException(ExceptionCode.DENIED_ACCESS.getMsg());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ValidateJwtTokenInterceptor.userThreadLocal.remove();
    }
}
